package com.bwie.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.mapper.OrderMapper;
import com.bwie.mapper.ShoppingCartMapper;
import com.bwie.mapper.UserMapper;
import com.bwie.pojo.Order;
import com.bwie.pojo.User;
import com.bwie.service.OrderService;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public List<Order> list() {
        return orderMapper.list();
    }

    @Override
    public void refund(Order order) {
        //修改库存
        orderMapper.refund(order);
        //退回余额
        orderMapper.refundPrice(order);
        //清除订单
        orderMapper.delOrder(order);

        //发送退款短信
        User user=shoppingCartMapper.findUserById(order.getUserId());

        rabbitTemplate.convertAndSend("", "sendMessage", JSONObject.toJSONString(user.getTel()), new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setMessageId(UUID.randomUUID().toString().replace("-",""));
                return message;
            }
        });
    }

    @Override
    public Order findByOrderId(Integer id) {
        return orderMapper.findByOrderId(id);
    }


}
